<template>
  <div class="address-container">
    <div class="header-actions">
      <el-button type="primary" icon="el-icon-plus" round @click="add">新增地址</el-button>
      <div class="action-group">
        <el-button type="success" icon="el-icon-download" round>导入</el-button>
        <el-button type="success" icon="el-icon-upload2" round>导出</el-button>
      </div>
    </div>

    <el-card class="address-table" shadow="hover">
    <el-table
        :data="tableData"
        v-loading="loading"
          stripe
          border>
      <el-table-column
          prop="name"
          label="收货人" align="center">
      </el-table-column>
      <el-table-column
          label="所在地区">
          <template #default="scope">
            {{ scope.row.province }} {{ scope.row.city }} {{ scope.row.district }}
          </template>
      </el-table-column>
      <el-table-column
            prop="detail"
          label="详细地址" width="300px">
      </el-table-column>
      <el-table-column
          prop="phone"
          label="手机号">
      </el-table-column>
      <!--     操作区域-->
      <el-table-column fixed="right" label="操作" align="center">
        <template #default="scope">
            <!--          这里scope.row传入直接传入一行的数据对象，可以使用row.username取出用户名的-->
          <el-button v-on:click="editeClick(scope.row)" type="primary" size="small">编辑</el-button>
          <el-popconfirm title="确定删除吗？" @confirm="deleteClick(scope.row.id)" style="margin-left: 10px">
            <template #reference>
              <el-button type="danger" size="small">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    </el-card>

    <!-- 分页和弹窗部分样式优化 -->
    <div class="pagination-container">
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-sizes="[5,10,20]"
          :page-size.sync="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalNumber">
      </el-pagination>
    </div>

    <el-dialog
        title="新增/修改地址"
        :visible.sync="dialogVisible"
        width="40%"
        :close-on-click-modal="false"
        center>
        <!--        输入表单-->
      <el-form v-bind:model="form" :rules="rules" ref="form" label-width="120px">
          <el-form-item label="地址信息：" :rules="[{ required: true}]">
          <el-cascader
            v-model="form.region"
            :options="options"
            :props="{ expandTrigger: 'hover' }"
            placeholder="请选择地区"
            @change="handleChange"
            ></el-cascader>
          </el-form-item>
          <el-form-item label="详细地址：" :rules="[{ required: true}]">
          <el-input type="textarea" v-model="form.detail" style="width: 80%"
                      placeholder="请输入详细地址信息，如道路、门牌号、小区、楼栋号、单元等信息"></el-input>
          </el-form-item>
          <el-form-item label="收货人姓名：" :rules="[{ required: true}]">
            <el-input v-model="form.name" style="width: 80%" placeholder="长度不超过25个字符"></el-input>
          </el-form-item>
          <el-form-item label="手机号码：" :rules="[{ required: true}]">
            <el-input v-model="form.phone" style="width: 80%" placeholder="请输入11位手机号"></el-input>
          </el-form-item>
        </el-form>
        <!--        下面的按钮-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import {
  pcaTextArr, // 省市区三级联动数据，纯汉字
} from "element-china-area-data";

export default {
  name: "AddressManage",

  created() {
    document.title = "地址管理"
    //从session中取出登陆者的信息
    let str = sessionStorage.getItem("user") || "{}";
    //解析str
    this.user = JSON.parse(str);
    this.loadData();
  },

  data() {
    return {
      // 选择的地区
      options: pcaTextArr, // 省市区三级联数据，纯汉字
      // 是否在加载
      loading: true,
      //新建一个表单，用来储存新增用户和修改用户的数据
      form: {},
      // 增加框是否可见
      dialogVisible: false,
      // 总数据数
      totalNumber: 400,
      // 当前页码
      currentPage: 1,
      // 一页多少个
      pageSize: 5,
      // 输入框的数据
      search: '',
      // 表格的数据
      tableData: [],
      // 登录用户
      user: {},
      rules: {
        name: [
          { required: true, message: '请输入收货人姓名', trigger: 'blur' },
          { max: 25, message: '长度不能超过25个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        detail: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ]
      }
    }
  },

  methods: {
    loadData() {
      this.loading = true
      request.get("/address", {
        params: {
          pageNum: this.currentPage,
          pageSize: this.pageSize,
          userId: this.user.id
        }
      }).then(res => {
        this.tableData = res.data.records;
        this.totalNumber = res.data.total;
        this.loading = false;
      })
    },

    add() {
      // 先清空表单
      this.form = {};
      // 再打开表单
      this.dialogVisible = true;
    },


    save() {
      // 修改地址处理逻辑
      if (this.form.region && this.form.region.length === 3) {
        this.form.province = this.form.region[0];
        this.form.city = this.form.region[1];
        this.form.district = this.form.region[2];
      } else {
        this.$message.error("请选择完整的地区信息");
        return;
      }

      // 检查详细地址
      if (!this.form.detail) {
        this.$message.error("请输入详细地址");
        return;
      }

      // 判断数据是否合法
      if (this.form.phone.length !== 11) {
        this.$message.error("请输入合法的11位手机号")
        return;
      }

      this.$message({
        type: "info",
        message: "马上保存/修改~"
      })
      this.form.userId = this.user.id;

      if (this.form.id) {
        //   有ID就更新
        request.put("/address", this.form).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "更新成功"
            })
            this.dialogVisible = false;
            this.loadData();  // 替代 location.reload()
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
        })
      } else {
        // 没有就新增
        request.post("/address", this.form).then(res => {
          if (res.code === '0') {
            this.$message({
              type: "success",
              message: "新增成功"
            })
            this.dialogVisible = false;
            this.loadData();  // 替代 location.reload()
          } else {
            this.$message({
              type: "error",
              message: res.msg
            })
          }
        });
      }
    },

    deleteClick(id) {
      request.delete('/address', {
        params: {
          id: id
        }
      }).then(res => {
        if (res.code === '0') {
          this.$message({
            type: "warning",
            message: "删除成功",
          })
          this.loadData();  // 替代 location.reload()
        } else {
          this.$message({
            type: "error",
            message: res.msg,
          })
        }
      });
    },

    editeClick(row) {
      // 将数据深拷贝过来，避免浅拷贝的修改问题
      this.form = JSON.parse(JSON.stringify(row));
      // 如果是编辑，需要设置 region 的值
      if (row.province && row.city && row.district) {
        this.form.region = [row.province, row.city, row.district];
      }
      this.dialogVisible = true;
    },

    // 表单每页大小的改变，因为有了双向绑定，直接更新一下数据就好了
    handleSizeChange() {
      this.loadData();
    },
    // 改变当前页码
    handleCurrentChange: function () {
      this.loadData();
    },

    // 添加地址选择处理方法
    handleChange(value) {
      console.log("选中的地区", value);
    },
  }
}

</script>

<style scoped>
.address-container {
  max-width: 1200px;
  margin: 25px auto;
  padding: 0 20px;
}

.header-actions {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
}

.action-group {
  display: flex;
  gap: 10px;
}

.address-table {
  margin-bottom: 20px;
  border-radius: 8px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}

/* 表单样式 */
.el-form-item {
  margin-bottom: 25px;
}

.el-input, .el-cascader {
  width: 100%;
}

/* 按钮样式 */
.el-button {
  padding: 12px 20px;
  font-weight: 500;
}

.el-button + .el-button {
  margin-left: 12px;
}

/* 表格内操作按钮 */
.el-table .el-button--small {
  padding: 8px 15px;
}

/* 对话框样式 */
.el-dialog {
  border-radius: 8px;
}

.el-dialog__header {
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.el-dialog__body {
  padding: 30px 20px;
}

.el-dialog__footer {
  padding: 20px;
  border-top: 1px solid #eee;
}
</style>